<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/15/0015
 * Time: 15:34
 */

namespace app\sports_admin\service;


use app\exception\GradeException;
use think\Request;
use app\sports_admin\model\Grade as GradeModel;
class Grade
{
    /*
     * 添加年级
     */
    public static function insert()
    {
        $input = self::getInfo();
        if(self::findGradeInfo($input['grade'])){
            throw new GradeException([
                'errorCode'=>400,
                'msg'=>"年级已存在"
            ]);
        }
        $bool = GradeModel::insertGradeInfo($input);
        if(!$bool){
            throw new GradeException([
                'errorCode'=>400,
                'msg'=>"添加失败"
            ]);
        }
        return json(['code'=>200,'msg'=>'添加成功']);
    }
    /*
     * 修改年级信息
     */
    public static function update()
    {
        $input = self::getInfo();
        //年级信息id
        $id = input('post.id');
        if(self::findGradeInfo($input['grade'])){
            throw new GradeException([
                'errorCode'=>400,
                'msg'=>"年级已存在"
            ]);
        }
        $bool = (new GradeModel())->save(['grade_title'=>$input['grade'],'type'=>$input['type'],'grade_name'=>$input['grade_name']],['id'=>$id]);
        if(!$bool){
            throw new GradeException([
                'errorCode'=>400,
                'msg'=>"修改失败"
            ]);
        }
        return json(['code'=>200,'msg'=>'修改成功']);
    }
    /*
     * 删除年级信息
     * @param $id 年级id
     */
    public static function delete()
    {
        $id = intval(input('post.id'));
        $bool = GradeModel::destroy($id);
        if(!$bool){
            throw new GradeException([
                'errorCode'=>400,
                'msg'=>"删除失败"
            ]);
        }
        return json(['code'=>200,'msg'=>'删除成功']);
    }
    /*
     * 获取年级信息
     */
    private static function getInfo()
    {
        return Request::instance()->only(['grade','type','grade_name']);
    }
    /*
     * 查询年级是否存在
     */
    private static function findGradeInfo($grade)
    {
        return GradeModel::findGrade($grade);
    }
}